<?php
/**
 * Usage:
 *
 * Permalink::add($regexp, array('varToMatch1', 'varToMatch2', ..., varToMatchN));
 */
class Permalink
{
  public static $rules;
  public static $queryvars;
  
  /**
   * addPermalink
   *
   * Adds a permalink redirection
   *
   * @param string $regexp Permalink regular expression
   * @param string $matches plain array with parameter names (order must match regexp)
   * @return void
   * @author Carlos
   */
  static public function add($regexp, $matches = null)
  {
    if (!self::$rules)
    {
      self::$rules = array();
      self::$queryvars = array();
      
      add_action('init',                   array(__CLASS__, 'flush'));
      add_action('generate_rewrite_rules', array(__CLASS__, 'register'));
      add_filter('query_vars',             array(__CLASS__, 'variables'));
    }
    
    foreach ((array) $matches as $i => $p)
    {
      if (!in_array($p, self::$queryvars))
        self::$queryvars[] = $p;
    }
    
    self::$rules[$regexp] = $matches;
  }
  
  //---------------------------------------------------------------- INTERNALS -
  
  static public function flush()
  {
    global $wp_rewrite;
    $wp_rewrite->flush_rules();
  }
  
  static public function register($wp_rewrite)
  {
    $rules = array();
    foreach (self::$rules as $regexp => $matches)
    {
      $params = count($matches) ? "?" : null;
      foreach ($matches as $i => $p)
      {
        if ($i)
          $params .= "&";
        $params .= "$p=".$wp_rewrite->preg_index($i+1);
      }
      
      $rules[$regexp] = "index.php".$params;
    }
    
    $wp_rewrite->rules = $rules + $wp_rewrite->rules;
  }
  
  static public function variables($vars)
  {
    return array_merge($vars, self::$queryvars);
  }
}